#include "ximage.h"
#include "xfileutils.h"
#include <Windows.h>
#include <string>
#include <wchar.h>

class BitmapDC
{
public:
    BitmapDC(HWND hwnd = NULL)
    : _hdc(NULL)
    , _bmp(NULL)
    , _font((HFONT)::GetStockObject(DEFAULT_GUI_FONT))
    , _hwnd(hwnd)
    {
        HDC hdc = ::GetDC(hwnd);
        _hdc = ::CreateCompatibleDC(hdc);
        ReleaseDC(hwnd, hdc);
    }

    ~BitmapDC()
    {
        prepareBitmap(0, 0);

        if (_hdc)
        {
            ::DeleteDC(_hdc);
        }

        HFONT defaultFont = (HFONT)::GetStockObject(DEFAULT_GUI_FONT);

        if (defaultFont != _font)
        {
            ::DeleteObject(_font);
            _font = defaultFont;
        }

        // release temp font resource
        if (_curFontPath.size() > 0)
        {
            wchar_t *buffer = utf8ToUtf16(_curFontPath);
            if (buffer)
            {
                ::RemoveFontResource(buffer);
                ::SendMessage(_hwnd, WM_FONTCHANGE, 0, 0);
                delete [] buffer;
                buffer = NULL;
            }
        }
    }

    wchar_t *utf8ToUtf16(std::string str)
    {
        wchar_t *buffer = NULL;
        do
        {
            if (str.size() < 0)
            {
                break;
            }
            // utf-8 to utf-16
            int length = str.size();
            int bufferLength  = length + 1;			
            buffer = new wchar_t[bufferLength];
            X_BREAK_IF(!buffer);
            memset(buffer, 0, bufferLength);
            length = ::MultiByteToWideChar(CP_UTF8, 0, str.c_str(), length, buffer, bufferLength);		
            buffer[length] = '\0';
        } while (0);

        return buffer;
    }

    bool prepareBitmap(int width, int height)
    {
        // release bitmap
        if (_bmp)
        {
            ::DeleteObject(_bmp);
            _bmp = NULL;
        }

        if (width > 0 && height > 0)
        {
            _bmp = ::CreateBitmap(width, height, 1, 32, NULL);
            
            if (!_bmp)
            {
                return false;
            }
        }

        return true;
    }

    X_SYNTHESIZE_READONLY(HDC, _hdc, DC);
    X_SYNTHESIZE_READONLY(HBITMAP, _bmp, Bitmap);

private:
    friend class xImage;
    HFONT _font;
    HWND _hwnd;
    std::string _curFontPath;
};

xImage::xImage()
: _width(0)
, _height(0)
, _bitsPerComponent(0)
, _data(0)
, _hasAlpha(false)
, _preMulti(false)
{

}

xImage::~xImage()
{
    X_SAFE_DELETE_ARRAY(_data);
}

bool xImage::initWithImageFile(const char *path, EImageFormat imageType /*= kFmtPng*/)
{
    bool ret = false;
    unsigned long size = 0;
    std::string fullPath = xFileUtils::sharedFiltUtils()->fullPathForFileName(path);

    return true;
}

